package com.kuisama.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 存储空间管理
 *
 * @author kuisama
 */
@Slf4j
public class AliyunOssBucketManager {
    private static final String SUCCESS = "success";
    private static final String FAILED = "failed";

    /**
     * 创建新的存储空间
     *
     * @param bucketName
     */
    public static String createBucket(OSSClient ossClient, String bucketName) {
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        // 设置存储空间的权限为公共读，默认是私有。
        createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
        // 设置存储空间的存储类型为低频访问类型，默认是标准类型。
        createBucketRequest.setStorageClass(StorageClass.IA);
        try {
            ossClient.createBucket(createBucketRequest);
            return SUCCESS;
        } catch (OSSException e) {
            log.error("error:{}", e.getMessage());
            return FAILED;
        }
    }

    /**
     * 列举存储空间
     *
     * @param bucketPrefix
     */
    public static List<Bucket> listBucket(OSSClient ossClient, String bucketPrefix) {
        ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
        // 列举指定前缀的存储空间。
        if (StringUtils.isNotBlank(bucketPrefix)) {
            listBucketsRequest.setPrefix(bucketPrefix);
        }
        try {
            return ossClient.listBuckets(listBucketsRequest).getBucketList();
        } catch (OSSException e) {
            log.error("error:{}", e.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 获取存储空间信息
     *
     * @param bucketName
     */
    public static Map getBucketInfo(OSSClient ossClient, String bucketName) {
        //判断空间是否存在
        boolean exists = ossClient.doesBucketExist(bucketName);
        if (!exists) {
            return new HashMap(1);
        }
        // 存储空间的信息包括地域（Region或Location）、创建日期（CreationDate）、拥有者（Owner）、权限（Grants）等。
        Map<String, Object> result = new HashMap<>(4);
        BucketInfo info = ossClient.getBucketInfo(bucketName);
        // 获取地域
        result.put("location", info.getBucket().getLocation());
        // 获取创建日期
        result.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:ss").format(info.getBucket().getCreationDate()));
        // 获取拥有者信息
        result.put("owner", info.getBucket().getOwner());
        // 获取权限信息
        AccessControlList acl = ossClient.getBucketAcl(bucketName);
        result.put("authority", acl.toString());
        return result;
    }

    /**
     * 删除存储空间
     *
     * @param bucketName
     */
    public static boolean deleteBucket(OSSClient ossClient, String bucketName) {
        //判断空间是否存在
        boolean exists = ossClient.doesBucketExist(bucketName);
        if (!exists) {
            return false;
        }
        // 删除存储空间
        ossClient.deleteBucket(bucketName);
        return true;
    }
}
